package icom.acm.manager;

import icom.acm.bean.T_EDUINFO;
import icom.acm.util.DBConnect;

import java.sql.Statement;
import java.sql.Timestamp;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

public class T_EduInfoMgr {
	public int insert(final T_EDUINFO edu){
		int flag = -1;
		String sql = "insert into T_EDUINFO(E_UID,E_CID,E_MAJOR,E_ENTRYDATE) " +
				"values(?, ?, ?, ?)";
		DBConnect db = new DBConnect();
		db.setAutoCommit(false);
		db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);		
		db.setInt(1, edu.getE_UID());
		db.setInt(2, edu.getE_CID());
		db.setString(3, edu.getE_MAJOR());
		db.setTimestamp(4, new Timestamp(edu.getE_ENTRYDATE().getTime()) );
		try {
			db.excute();
			flag = db.getGeneratedKeys();
			db.commit();
		} catch (MySQLIntegrityConstraintViolationException e) {
			// 数据重复
			flag = -1;
		} finally{
			db.setAutoCommit(true);
			db.close();
		}
		return flag;
	}
	
	public int update(final T_EDUINFO edu){
		int flag = -1;
		String sql = "UPDATE T_EDUINFO SET E_CID=?," +
				" E_MAJOR=?, E_ENTRYDATE=? WHERE E_UID=?";
		DBConnect db = new DBConnect();
		db.setAutoCommit(false);
		db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
		db.setInt(1, edu.getE_CID());
		db.setString(2, edu.getE_MAJOR());
		db.setTimestamp(3, new Timestamp(edu.getE_ENTRYDATE().getTime()) );
		db.setInt(4, edu.getE_UID());
		try {
			db.excute();
			flag = db.getGeneratedKeys();
			db.commit();
		} catch (MySQLIntegrityConstraintViolationException e) {
			// 数据重复
			flag = -1;
		} finally{
			db.setAutoCommit(true);
			db.close();
		}
		return flag;
	}
	public void delete(final int uid, final int cid){
		final DBConnect db = new DBConnect();
		final String sql = "DELETE FROM T_EDUINFO WHERE E_UID = ? AND E_CID=?";
		System.out.println(sql);
		db.setAutoCommit(false);
		db.prepareStatement(sql);
		db.setInt(1, uid);
		db.setInt(2, cid);
		try {
			db.excute();
			db.commit();
		} catch (final Exception ex) {
			ex.printStackTrace();
		} finally {
			db.setAutoCommit(true);
			db.close();
		}
	}
}
